# -*- coding: utf-8 -*-
# created by Alberthch - 陈航  2021/7/15 15:20
# Description:怎样从一个集合中获得最大的或者最小的N个元素


import heapq

portfolio = [
   {'name': 'IBM', 'shares': 100, 'price': 91.1},
   {'name': 'AAPL', 'shares': 50, 'price': 543.22},
   {'name': 'FB', 'shares': 200, 'price': 21.09},
   {'name': 'HPQ', 'shares': 35, 'price': 31.75},
   {'name': 'YHOO', 'shares': 45, 'price': 16.35},
   {'name': 'ACME', 'shares': 75, 'price': 115.65}
]
# 直接调用堆函数，会先生成一个大顶堆或者小顶堆然后进行堆顶元素进行弹出
# lambda表达式中s表示集合中的元素
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])

print(cheap)
print(expensive)

